﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using LitJson;
using System;


public class MsgPanel : MonoBehaviour
{
    public class MsgInfo
    {
        public string strMsg;
        public string strSendTime;
        public string strMsgOwner;
        public string strMsgTarget;
        public string strMsgType;

        public MsgInfo(string content, string sendTime, string target, string owner, string type)
        {
            strMsg = content;
            strSendTime = sendTime;
            strMsgOwner = owner;
            strMsgTarget = target;
            strMsgType = type;
        }
    }
    public GameObject objMsg;
    public InputField inputField;
    public ScrollRect scrollRect;
    public Text txtTitle;
    public Text txtTip;

    string strTargetIP = string.Empty;
    Action<string> closeFun;
    List<MsgInfo> vecMsg = new List<MsgInfo>();
    bool bRun = true;

    // Start is called before the first frame update
    void Start()
    {
        objMsg.SetActive(false);
        inputField.text = string.Empty;
    }

    private void OnEnable()
    {
        StartCoroutine("UpdateMsg");
    }

    private void OnDisable()
    {
        StopAllCoroutines();
    }

    public void Init(string target, string title, Action<string> closeFun)
    {

        strTargetIP = target;
        this.closeFun = closeFun;
        txtTitle.text = "<color=#00FF00>" + title + "</color>";
    }

    private void OnDestroy()
    {
        bRun = false;
    }
    IEnumerator UpdateMsg()
    {
        while (bRun)
        {
            if (vecMsg.Count > 0)
            {
                MsgInfo msgInfo = null;
                lock (vecMsg)
                {
                    msgInfo = vecMsg[0];
                    vecMsg.RemoveAt(0);
                }
                if (msgInfo != null)
                {
                    var obj = Instantiate(objMsg, objMsg.transform.parent);
                    obj.SetActive(true);
                    var txt = obj.GetComponent<Text>();
                    if (msgInfo.strMsgTarget == strTargetIP)
                    {
                        lock (Broadcast.clientInfoSelf)
                        {
                            txt.text = "<color=#519BFF><size=20>" + msgInfo.strSendTime + "</size> : <" + Broadcast.clientInfoSelf.strHostName + "></color>\r\n" + msgInfo.strMsg + "\r\n";
                        }
                        txt.alignment = TextAnchor.UpperRight;
                    }
                    else
                    {
                        txt.text = "<color=#00FF00><" + txtTitle.text + "> : <size=20>" + msgInfo.strSendTime + "</size></color>\r\n" + msgInfo.strMsg + "\r\n";
                        txt.alignment = TextAnchor.UpperLeft;
                    }
                    obj.GetComponent<MsgItem>().strContent = msgInfo.strMsg;
                    obj.GetComponent<MsgItem>().clickFun = (string c) =>
                    {
                        StartCoroutine(ShowTip(c));
                    };
                    yield return null;

                    obj.GetComponent<RectTransform>().sizeDelta = new Vector2(AppView.fWS - 20f/*20是滚动条宽*/, txt.preferredHeight);
                    yield return null;

                    scrollRect.verticalNormalizedPosition = 0f;
                    Debug.Log("MsgPanel:: " + txt.alignment + "   " + strTargetIP + "    " + msgInfo.strMsgOwner + "    " + msgInfo.strMsg + " size:" + txt.preferredHeight);
                }
            }
            yield return new WaitForSeconds(0.5f);
        }
    }

    IEnumerator ShowTip(string t)
    {
        txtTip.text = t;
        txtTip.gameObject.SetActive(true);
        yield return new WaitForSeconds(1f);
        txtTip.gameObject.SetActive(false);
    }

    public void OnEndEditorCB()
    {
        if (inputField.text != string.Empty)
        {
            JsonData json = new JsonData();
            json["msg"] = Protocol.EMProtocol.talk.ToString();
            json["content"] = inputField.text;
            json["send_time"] = System.DateTime.Now.ToString("G");
            json["target"] = strTargetIP;
            json["owner"] = Broadcast.clientInfoSelf.strIP;
            json["type"] = "txt";

            Broadcast.SendUDPMsg(json.ToJson(), strTargetIP);
            inputField.text = string.Empty;

            AddMsg(new MsgInfo(json["content"].ToString(), json["send_time"].ToString(), strTargetIP, Broadcast.clientInfoSelf.strIP, json["type"].ToString()));
        }
    }

    public void AddMsg(MsgInfo msg)
    {
        lock (vecMsg)
        {
            vecMsg.Add(msg);
        }
    }

    public void OnReturnClickCB()
    {
        closeFun?.Invoke(strTargetIP);
        gameObject.SetActive(false);
    }
}
